<?php
/**
 * description
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     weiyizheng
 * @date       2022/11/9
 * @time       3:05 下午
 */

namespace Buu\Modules\EsStandard\Controllers;


use App\Admin\Extensions\Tools\UserButton;
use App\Http\Controllers\Controller;
use App\Models\DbInstance;
use App\Models\DbTables;
use App\Models\EsColumn;
use App\Models\EsFilterRule;
use App\Models\EsIndex;
use App\Models\EsSourceMapping;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Form\NestedForm;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class EsDbMappingController extends Controller
{
	public function add(Request $request, Content $content, $id, $sid = 0)
	{
		$esIndex = EsIndex::find($id)->toArray();

		$form = $this->mappingForm($id, $sid);

		return $content
			->header('添加映射')
			->description($esIndex['name'])
			->breadcrumb([
				'text' => 'Es映射管理',
				'url' => '/EsStandard/es-index/' . $id . '/mapping/edit#tab_mapping'
			], ['text' => '添加映射'])
			->body($form);
	}

	public function edit(Request $request, Content $content, $id, $sid)
	{
		$esIndex = EsIndex::find($id)->toArray();
		$form = $this->mappingForm($id, $sid);
		return $content
			->header('编辑映射')
			->description($esIndex['name'])
			->breadcrumb([
				'text' => 'Es映射管理',
				'url' => '/EsStandard/es-index/' . $id . '/mapping/edit#tab_mapping'
			], ['text' => '编辑映射']
			)
			->body($form);
	}

	public function save(Request $request, $id)
	{
		$res = $request->all();
		$data = [
			'es_index_id' => $id,
			'db_tables_id' => $res['db_tables_id'] ?? 0,
			'db_column_name' => $res['db_column_name'] ?? '',
			'es_column_name' => $res['es_column_name'] ?? '',
			'mapping_type' => $res['mapping_type'] ?? 0,
			'is_main_table' => $res['is_main_table'] ?? 0,
			'is_must' => $res['is_must'] ?? 0
		];

		if (!empty($res['es_source_id'])) {
			$msg = '编辑成功';
			// 编辑
			$data['update_time'] = time();
			$data['update_username'] = Admin::user()->username;

			EsSourceMapping::where('id', $res['es_source_id'])->update($data);
		} else {
			$msg = '添加成功';
			// 新增
			$data['add_username'] = Admin::user()->username;
			$data['update_username'] = Admin::user()->username;
			$data['add_time'] = time();
			$data['update_time'] = time();

			EsSourceMapping::insert($data);
		}
		$this->saveFilterRule($id, $res['db_tables_id'], $res);

		admin_toastr($msg, 'success', ['timeOut' => 3]);
		return redirect("/admin/EsStandard/es-index/{$id}/mapping/edit");
	}

	public function saveFilterRule($indexId, $dbId, $res)
	{
		// 删除之前的过滤条件
		EsFilterRule::query()->where(['es_index_id' => $indexId, 'db_tables_id' => $dbId])->delete();

		// 全部新建
		$data = [];
		if (!empty($res['filter'])) {
			foreach ($res['filter'] as $k => $v) {
				if ($v['_remove_']) continue;
				if (!empty($v['raw_sql'])) {
                    $v['condition_column_name'] = '';
					$v['condition'] = '';
					$v['value'] = '';
                }
				$data[] = [
					'es_index_id' => $indexId,
					'db_tables_id' => $dbId,
					'column_name' => $v['condition_column_name'] ?? '',
					'condition' => $v['condition'] ?? '',
					'value' => $v['value'] ?? '',
                    'raw_sql' => $v['raw_sql'] ?? '',
				];
			}
			EsFilterRule::insert($data);
		}
	}

	public function delete($id, $sid)
	{
		$msg = '删除成功';
		if (!empty($sid)) {
			if (EsSourceMapping::query()->find($sid)->delete()) {
				admin_toastr($msg, 'success', ['timeOut' => 3]);
			} else {
				admin_toastr('删除失败', 'error', ['timeOut' => 3]);
			}
		} else {
			admin_toastr('删除失败', 'error', ['timeOut' => 3]);
		}
		return redirect("/admin/EsStandard/es-index/{$id}/mapping/edit");
	}

	public function mappingForm($id, $sid = 0)
	{
		$esIndex = EsIndex::query()->find($id)->toArray();

		$form = new Form(new EsSourceMapping());
		$form->footer(function (Form\Footer $footer) {
			$footer->disableEditingCheck();
			$footer->disableCreatingCheck();
			$footer->disableViewCheck();
		});
		$form->tools(function (Form\Tools $tools) {
			$tools->disableDelete();
			$tools->disableView();
			$tools->disableList();
		});
		$form->html("<p><h5><b>{$esIndex['name']}</b></h5></p>", 'Es索引名')->disable()->setWidth(4, 2);
//		$form->select('es_column_name', 'Es字段')->options(
//			EsColumn::where('es_index_id', $id)->get()->pluck('column_name', 'column_name')
//		)->required()->setWidth(4, 2);
		$form->text('es_column_name', 'Es字段')->setWidth(4, 2)->required();
		$form->divider();
		$form->select('db_tables_id', '映射数据表')->options(
			DbTables::all()->pluck('table_name', 'id')
		)->loads(['db_column_name', 'condition_column_name'], ['/admin/EsStandard/db-tables/getColumns', '/admin/EsStandard/db-tables/getColumns'])->required()->setWidth(4, 2);
		$form->select('db_column_name', '映射db字段')->options(function () {
			if ($this->db_tables_id) {
				$dbTable = DbTables::query()->find($this->db_tables_id)->toArray();
				return DbInstance::getColumnsById($dbTable['db_instance_id'], $dbTable['database'], $dbTable['tables'][0]);
			} else {
				return [];
			}
		})->required()->setWidth(4, 2);
		$form->select('mapping_type', '映射类型')->options(EsSourceMapping::MAPPING_TYPE)->default(1)->required()->setWidth(4, 2);
		$form->radio('is_main_table', '是否是主表')->options([
			1 => '是',
			0 => '否'
		])->default(0)->required()->help("指此Es索引是否是以这张映射表的数据为基础");
		$form->radio('is_must', '相对于Es是否必须')->options([
			1 => '是',
			0 => '否'
		])->default(0)->required()->help("指同步Es时这个字段是不是必须的");
		if ($sid) {
			$form->divider('过滤条件');
			$form->table('filter', '', function (NestedForm $nest) use ($id) {
				$nest->hidden('es_index_id')->default($id);
				$nest->select('condition_column_name', '字段')->options(function () {
					if ($this->db_tables_id) {
						$dbTable = DbTables::find($this->db_tables_id)->toArray();
						return DbInstance::getColumnsById($dbTable['db_instance_id'], $dbTable['database'], $dbTable['tables'][0]);
					} else {
						return [];
					}
				});
				$nest->select('condition', '条件')->options(EsFilterRule::ENUM_CONDITION);
				$nest->text('value', '值');
				$nest->text('raw_sql', '原生SQL语句')->placeholder('原生sql优先于字段筛选');
			});
		}
		$form->setAction("/admin/EsStandard/es-db-mapping/{$id}/save");

		if ($sid) {
			$form->edit($sid);
			$form->hidden('es_source_id')->value($sid);
		}

		return $form;
	}


    public function getDbTablesIds(Request $request)
    {
        $result = [];
        $id = $request->get('q');
        if (!$id) {
            return $result;
        }
        $dbTablesIds = EsSourceMapping::where('es_index_id', $id)->distinct()->get('db_tables_id')->toArray();
        if (empty($dbTablesIds)) {
            return $result;
        }

        $data = DbTables::query()->whereIn('id', array_column($dbTablesIds, 'db_tables_id'))->get()->toArray();
        foreach ($data as $val) {
            $result[$val['id']] = $val['table_name'];
        }
        return $result;

    }
}